import React, { useEffect, useState } from "react";
import { Button, Input, message } from "antd";
import useWebSocket, { ReadyState } from "react-use-websocket";
import { v4 as uuidv4 } from "uuid";
import { downloadPcap, query } from "../../api/ApiPacket";
import { ServiceResult } from "../../utils/axiosInstance";
import { PcapResult } from "../../entity/Summary";
import useGlobalStore from "../../store/UseGlobalStore";
import { productIp } from "../../productUrl";

export const FilterHeight = 30;

// export const wsBaseUrl = 'ws://localhost:9998/ws/admin/websocket/';
const isDev = process.env.NODE_ENV === "development";

export const wsBaseUrl = isDev
  ? "ws://localhost:9998/ws/admin/websocket/"
  : `ws://${productIp}:9998/ws/admin/websocket/`;
const Filter = () => {
  const [clientId, setClientId] = useState(uuidv4());
  const { setPcapResult, pcapResult, setLoading, setDownloadStream } =
    useGlobalStore();
  const [checked, setChecked] = useState(false);
  // const [input, setInput] = useState('');
  const [input, setInput] = useState('6506348427466723052,6506348414581808400')
  // const [input, setInput] = useState("6506348427466723052");
  const [socketUrl, setSocketUrl] = useState(wsBaseUrl + clientId);
  const { sendMessage, lastMessage, readyState } = useWebSocket(socketUrl);
  const [requestDateFromProxyId, setRequestDateFromProxyId] = useState<
    undefined | string
  >(undefined);
  const connectionStatus = {
    [ReadyState.CONNECTING]: "Connecting",
    [ReadyState.OPEN]: "Open",
    [ReadyState.CLOSING]: "Closing",
    [ReadyState.CLOSED]: "Closed",
    [ReadyState.UNINSTANTIATED]: "Uninstantiated",
  }[readyState];
  useEffect(() => {
    if (lastMessage) {
      let response: ServiceResult<PcapResult> = JSON.parse(lastMessage.data);
      if (response.success) {
        let data = response.data;
        setPcapResult(data);
      } else {
        message.error(response.msg);
        setPcapResult(undefined);
      }
      setLoading(false);
    }
  }, [lastMessage]);

  return (
    <div
      style={{ height: FilterHeight, display: "flex", alignItems: "center" }}
    >
      <Button
        disabled={input.length < 19}
        onClick={async () => {
          setPcapResult(undefined);
          setLoading(true);
          let s = input
            .trim()
            .split(",")
            .map((x) => x.trim())
            .join(",");
          let { data, success } = await query({
            cdrStrs: s,
            clientId: clientId,
            cdrId: "dudu",
            packetUniqueId: uuidv4(),
          });
          if (success) {
            console.log("clientId", clientId);
            console.log("data", data);
            let id = data
              .split("\n")
              .map((x) => x.trim())[3]
              .split(":")[1]
              .trim();
            setRequestDateFromProxyId(id);
          } else {
            setLoading(false);
          }
        }}
        type={"default"}
        size={"small"}
      >
        查询
      </Button>
      {/*<span style={{color: 'red'}}> {readyState}- {connectionStatus}  </span>*/}

      {/*<Button type={"default"} size={'small'} onClick={() => sendMessage("dudu")}>64位cdr查询</Button>*/}
      {/*<Button type={"default"} size={'small'}>128位cdr查询</Button>*/}
      {/*<Button type={"default"} size={'small'}>imsi查询</Button>*/}
      {/*<Checkbox style={{marginLeft: 10}} checked={checked} onChange={e => setChecked(e.target.checked)}>c</Checkbox>*/}
      <Button
        type={"default"}
        size={"small"}
        onClick={() => {
          setInput("");
          setPcapResult(undefined);
        }}
      >
        清空
      </Button>
      <span style={{ marginLeft: 10 }}>Cdr:</span>

      <Input
        style={{ width: 400 }}
        value={input}
        onChange={(e) => {
          setInput(e.target.value);
        }}
        size={"small"}
      />
      <Button
        type={"default"}
        disabled={!pcapResult}
        size={"small"}
        onClick={async () => {
          if (pcapResult && requestDateFromProxyId) {
            downloadPcap(requestDateFromProxyId).then((response) => {
              const fileURL = window.URL.createObjectURL(
                new Blob([response.data])
              );
              const fileLink = document.createElement("a");

              fileLink.href = fileURL;
              fileLink.setAttribute("download", `${input}.pcap`);
              document.body.appendChild(fileLink);

              fileLink.click();
            });
          }
        }}
      >
        下载Pcap包
      </Button>
      <Button
        type={"default"}
        disabled={!pcapResult}
        size={"small"}
        onClick={() => {
          setDownloadStream(uuidv4());
        }}
      >
        下载时序图
      </Button>
    </div>
  );
};

export default Filter;
